package com.eeepay.eeepay_v2.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.MerchantCollectListAdapter;
import com.eeepay.eeepay_v2.model.MerchantQueryCri;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshBase;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshListView;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ScreenSwitch;
import com.eeepay.v2_library.view.LeftRightText;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerchantSuperSearch;
import cn.eeepay.api.grpc.nano.MerchantSuperSearchServiceGrpc;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/10 0010.\
 * 商户超级查询汇总
 */
public class MerchantCollectActivity extends ABBaseActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private static final int AGENT_COLLECT = 1;//代理商汇总
    private static final int HP_COLLECT = 2;//产品汇总

    private TextView tv_back, tv_company;
    private RadioGroup top_group;//代理商汇总、产品汇总
    private LeftRightText lrt_sum;
    private PullToRefreshListView lv_content;
    private MerchantCollectListAdapter agentAdapter, hpAdaper;//按代理商汇总和按产品汇总
    private MerchantQueryCri merchantQueryCri;
    private String flag;//区分是1代理商汇总还是2产品汇总
    private int merchantSum;//商户总数
    private int agentCurrPage = 1;
    private int hpCurrPage = 1;
    private int ageTotal, proTotal;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_merchant_collect;
    }

    @Override
    protected void initWidget() {
        tv_back = getViewById(R.id.tv_back);
        top_group = getViewById(R.id.radio_group);
        lv_content = getViewById(R.id.lv_content);
        lrt_sum = getViewById(R.id.lrt_sum);
        agentAdapter = new MerchantCollectListAdapter(mContext);
        hpAdaper = new MerchantCollectListAdapter(mContext);
        lv_content.setAdapter(agentAdapter);
        flag = "1";

        merchantQueryCri = (MerchantQueryCri) bundle.getSerializable(Constant.MERCHANT_QUERY_CRI);
        sendHttpRequest(AGENT_COLLECT);
        sendHttpRequest(HP_COLLECT);
    }

    @Override
    protected void eventOnClick() {
        tv_back.setOnClickListener(this);
        top_group.setOnCheckedChangeListener(this);
        top_group.check(top_group.getChildAt(0).getId());

        lv_content.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        lv_content.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if ("1".equals(flag)) {
                    if (ageTotal > agentCurrPage * 10) {
                        agentCurrPage++;
                        sendHttpRequest(AGENT_COLLECT);
                    } else {
                        showToast("已经是最后一页了");
                        if (lv_content.isRefreshing()) {
                            lv_content.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    lv_content.onRefreshComplete();
                                }
                            }, 500);
                        }
                    }

                } else {
                    if (proTotal > hpCurrPage * 10) {
                        hpCurrPage++;
                        sendHttpRequest(HP_COLLECT);
                    } else {
                        showToast("已经是最后一页了");
                        if (lv_content.isRefreshing()) {
                            lv_content.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    lv_content.onRefreshComplete();
                                }
                            }, 500);
                        }
                    }

                }
            }
        });
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                MerchantSuperSearch.MerchantSuperSearchRequest request = new MerchantSuperSearch
                        .MerchantSuperSearchRequest();
                //1按代理商汇总2按产品汇总
                switch (taskId) {
                    case AGENT_COLLECT:
                        request.aggregate = "1";
                        request.page = agentCurrPage;
                        break;
                    case HP_COLLECT:
                        request.aggregate = "2";
                        request.page = hpCurrPage;
                        break;
                }
                request.agentNode = merchantQueryCri.getAgentNode();
                request.mobilephone = merchantQueryCri.getPhone();
                request.includeSon = "1";
                request.bpId = merchantQueryCri.getDeviceName();
                request.mobilephone = merchantQueryCri.getPhone();
                request.includeSon = "1";
                request.tranTimeStar = merchantQueryCri.getTradeStartTime();
                request.tranTimeEnd = merchantQueryCri.getTradeEndTime();
                request.tranAmountStar = merchantQueryCri.getTradeMinMoney();
                request.tranAmountEnd = merchantQueryCri.getTradeMaxMoney();
                if (!TextUtils.isEmpty(merchantQueryCri.getTradeMinCount())) {
                    request.tranCountStar = merchantQueryCri.getTradeMinCount();
                }
                if (!TextUtils.isEmpty(merchantQueryCri.getTradeMaxCount())) {
                    request.tranCountEnd = merchantQueryCri.getTradeMaxCount();
                }
                request.province = merchantQueryCri.getProvince();
                request.city = merchantQueryCri.getCity();
                request.district = merchantQueryCri.getDistrict();
                request.pdbStartDate = merchantQueryCri.getIntoStartTime();
                request.pdbEndDate = merchantQueryCri.getIntoEndTime();
                request.merchantStatus = merchantQueryCri.getMerchantStatus();
                request.noBpId = merchantQueryCri.getNoOpenDevice();

                request.size = 10;
                MerchantSuperSearchServiceGrpc.MerchantSuperSearchServiceBlockingStub stub =
                        MerchantSuperSearchServiceGrpc.newBlockingStub(channel)
                                .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                MerchantSuperSearch.MerchantSupAggregateResponse response = stub.merchantSuperSearchAggregate(request);
                return response;

            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (lv_content.isRefreshing()) {
                    lv_content.onRefreshComplete();
                }
                if (result == null) {
                    showToast("查询数据出错");
                    return;
                }
                MerchantSuperSearch.MerchantSupAggregateResponse response = (MerchantSuperSearch.MerchantSupAggregateResponse) result;
                merchantSum = response.merchantSum;
                lrt_sum.setRightText(merchantSum + "个商户");
                switch (taskId) {
                    case AGENT_COLLECT:
                        ageTotal = response.total;
                        if (agentCurrPage == 1) {
                            agentAdapter.setList(Arrays.asList(response.merchantAggregateInfo));
                        } else {
                            agentAdapter.addAll(Arrays.asList(response.merchantAggregateInfo));
                        }
                        break;
                    case HP_COLLECT:
                        proTotal = response.total;
                        if (hpCurrPage == 1) {
                            hpAdaper.setList(Arrays.asList(response.merchantAggregateInfo));
                        } else {
                            hpAdaper.addAll(Arrays.asList(response.merchantAggregateInfo));
                        }
                        break;
                }
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.btn_1:
                lv_content.setAdapter(agentAdapter);
                flag = "1";
                break;
            case R.id.btn_2:
                flag = "2";
                lv_content.setAdapter(hpAdaper);
                break;
            case R.id.tv_back:
                finish();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                ScreenSwitch.finish(mContext);
                break;
        }
    }
}
